import CustomEvent = WechatMiniprogram.CustomEvent;
import {BasePageData} from "../common/core/BasePage";
import {field} from "../../modules/coreModule/data/DataLoader";
import {Certification} from "../../modules/userModule/data/User";
import {Role, roleRepo} from "../../modules/userModule/data/Role";
import {Locations} from "../../utils/Locations";
import {MediaFile} from "../../utils/CloudFileUtils";
import {page, pageFunc} from "../common/PageBuilder";
import {ItemDetailPage} from "../common/pages/ItemDetailPage";
import {UserPage} from "../common/partPages/UserPage";
import {PickerPage} from "../common/partPages/PickerPage";
import {UploaderPage} from "../common/partPages/UploaderPage";
import {userMgr, waitForLogin} from "../../modules/userModule/managers/UserManager";
import {waitForDataLoad} from "../../modules/coreModule/managers/DataManager";
import {alertMgr, handleError} from "../../modules/coreModule/managers/AlertManager";
import {TemplateIds} from "../../modules/messageModule/MessageCommon";
import {PK} from "../../modules/coreModule/data/BaseData";

class Data extends BasePageData {

	@field(Certification)
	item: Certification;

	@field([Role])
	roles: Role[] = [];
	@field
	roleIdx: number = 0;

	@field
	locations = Locations;

	@field([Object])
	images: MediaFile[] = []

	@field([Object])
	licenseImg:	MediaFile[] = []

	@field([Object])
	certificationImg:	MediaFile[] = []

	@field
	readonly: boolean = false;
}

const RoleAuthTitle = "选择认证角色";
const LocationTitle = "选择地点";

class Param {
	certification: Certification
}

@page("certAuth", "企业认证")
export class CertAuthPage extends ItemDetailPage<Data, Certification, Param> {

	public data = new Data();

	/**
	 * 部分页
	 */
	public userPage: UserPage = new UserPage();
	public pickerPage: PickerPage = new PickerPage();
	public uploaderPage: UploaderPage = new UploaderPage("cert", "cert");

	/**
	 * 初始化
	 */
	onLoad(e) {
		super.onLoad(e);
		this.loadData().then();
	}

	/**
	 * 数据加载完成回调
	 */
	@waitForLogin
	@waitForDataLoad
	private loadData() {
		let item = new Certification();
		let readonly = false;
		let roleIdx = 1;
		const roles = roleRepo().findByNeedAuth(true)
		//	已认证
		if (this.params?.certification){
			item = this.params.certification;
			readonly = true;
			roleIdx = roles.findIndex((role)=>{
				return role._id == item.roleId;
			})
		}else{
			//item.roleId = roles[0]._id;
			item.roleId = roles[1]._id;
		}
		return this.setData({
			item, roles, roleIdx, readonly
		})
	}

	// TODO: 添加各个字段的输入交互

	// region 输入字段交互

	@pageFunc
	public onNameChange(e: CustomEvent<any>) {
		this.setItemData({name: e.detail}).then();
	}

	@pageFunc
	public onNoteChange(e: CustomEvent<any>) {
		//bind:blur事件的返回值是 event.detail = {value,cursor}
		this.setItemData({note: e.detail.value}).then();
	}

	// endregion

	// region 地点控制

	// /**
	//  * 地点点击回调
	//  */
	// @pageFunc
	// public async onLocationTap() {
	// 	const locIdxs = await this.pickerPage.startPicker(
	// 		LocationTitle, this.data.locations);
	// 	if (!locIdxs) return;
	//
	// 	// let result: string = this.data.locations[locIdxs[0]].name + " " +
	// 	// 	this.data.locations[locIdxs[0]].sub[locIdxs[1]].name +
	// 	// 	('sub' in this.data.locations[locIdxs[0]].sub[locIdxs[1]] ?
	// 	// 	" " + this.data.locations[locIdxs[0]].sub[locIdxs[1]].sub[locIdxs[2]].name : "");
	// 	//
	// 	// this.setItemData({location: result}).then();
	//
	// 	const province = Locations[locIdxs[0]];
	// 	const city = province.sub[locIdxs[1]];
	// 	const region = city.sub?.[locIdxs[2]];
	//
	// 	await this.setItemData({
	// 		location: `${province.name} ${city.name} ${region?.name || ""}`
	// 	})
	// }

	// endregion

	// region 角色控制

	/**
	 * 角色名称数组
	 */
	public roleTexts() {
		return this.data.roles.map(r => ({name: r.name}));
	}

	/**
	 * 角色点击回调
	 * 当前只可选择企业
	 */
	@pageFunc
	public async onRoleTap() {
		return;
		// if (this.data.readonly) return;
		// const roleIdxs = (await this.pickerPage.startPicker(
		// 	RoleAuthTitle, this.roleTexts(), this.data.roleIdx));
		// if (roleIdxs == null) return;
		//
		// const roleId = this.data.roles[roleIdxs[0]]._id;
		// await this.setData({roleIdx: roleIdxs[0]});
		// await this.setItemData({roleId})
	}

	// endregion

	/**
	 * 提交
	 */
	@pageFunc
	@handleError
	public submit() {
		this.check();
		wx.requestSubscribeMessage({
			tmplIds: [TemplateIds["审核通知"]],
			success: this.doSubmit.bind(this)
		})
	}
	@handleError
	private async doSubmit() {
		await this.uploadPictures();
		await userMgr().authCert(this.item);
		if(await alertMgr().showAlert("信息已提交！"))
			this.back();
	}

	/**
	 * 校验格式
	 */
	private check() {
		// if (this.data.roles[this.data.roleIdx].name == "教官" && !this.item.location) throw "请选择期望地区";
		if (!this.item.images) throw "请上传认证文件";
	}

	/**
	 * 下载授权书
	 */
	@pageFunc
	public async onDownload() {
		const url = "https://6a75-junxuntong-8g88o26yce05bb47-1310094760.tcb.qcloud.la/%E4%BC%81%E4%B8%9A%E8%AE%A4%E8%AF%81.pdf?sign=d9abd2942d6a848e6afb82c559a990fc&t=1672049447";
		console.log("onDownload", url);
		wx.downloadFile({
			url, // 下载url
			filePath: wx.env.USER_DATA_PATH + '/企业认证授权书模板.pdf',
			success (res) {
				console.log('res',res)
				if (res.statusCode == 200) {
					console.log('res.statusCode',res)
					const filePath = res.filePath;
					wx.openDocument({
						filePath,
						showMenu: true,
						fileType: 'pdf',
						success: function(ress) {
							console.log('打开文档成功',ress)
						},
						fail: function(err) {
							console.log('保存失败：', err)
						}
					})
				}
			},
			fail: console.error,
		})
	}

	/**
	 * 上传图片
	 */
	private async uploadPictures() {
		await this.processImages();
		const fileIds = await this.uploaderPage.uploadPictures();
		await this.setItemData({images: fileIds});
	}

	private async processImages(){
		this.data.images.push(this.data.certificationImg[0]);
		this.data.images.push(this.data.licenseImg[0]);
		await this.setData({images:this.data.images})
	}

	@pageFunc
	public async onCertificationChoose(e: CustomEvent){
		this.data.certificationImg.push(e.detail.file);
		await this.setData({certificationImg:this.data.certificationImg})
	}

	@pageFunc
	public async onLicenseChoose(e: CustomEvent){
		this.data.licenseImg.push(e.detail.file);
		await this.setData({licenseImg:this.data.licenseImg})
	}

	@pageFunc
	public async onCertificationDelete(e: CustomEvent){
		this.data.certificationImg.pop();
		await this.setData({certificationImg:this.data.certificationImg})
	}

	@pageFunc
	public async onLicenseDelete(e: CustomEvent){
		this.data.licenseImg.pop();
		await this.setData({licenseImg:this.data.licenseImg})
	}

}
